package com.ai.exam.controller;

import com.ai.exam.dto.WxModel;
import com.ai.exam.util.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("wx")
public class WxController  {

    private Logger logger = LoggerFactory.getLogger(WxController.class);
    @Value("${my-moblie.appid}")
    private String appid;
    @Value("${my-moblie.accountID}")
    private String  accountID;
    @Value("${my-moblie.backBaseUrl}")
    private String backBaseUrl;
    @Value("${my-moblie.forendUrl}")
    private String forendUrl;
    @Value("${my-moblie.authorize}")
    private String authorize;
    @Value("${my-moblie.getFansInfoByOauth2}")
    private String getFansInfoByOauth2;
    @Value("${my-moblie.sendCaptcha}")
    private String sendCaptcha;
    @Value("${my-moblie.telbindbycaptcha}")
    private String telbindbycaptcha;
    @Value("${my-moblie.getJsSignature}")
    private String getJsSignature;

    //获取token
    @GetMapping("getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("进入getCode");
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        //这里要将你的授权回调地址处理一下，否则微信识别不了
        String redirect_uri= URLEncoder.encode(backBaseUrl+"wx/getCodeBack", "UTF-8");
        //简单获取openid的话参数response_type与scope与state参数固定写死即可
        StringBuffer url=new StringBuffer(authorize+"?redirect_uri="+redirect_uri+
                "&appid="+appid+"&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
        response.sendRedirect(url.toString());//这里请不要使用get请求单纯的将页面跳转到该url即可

//        Map map = new HashMap();
//        map.put("redirect_uri",backBaseUrl+"wx/getCodeBack");
//        map.put("appid",appid);
//        map.put("response_type","code");
//        map.put("scope","snsapi_base");
//        map.put("state","123#wechat_redirect");
//        String rs = HttpUtil.restTemplate("https://open.weixin.qq.com/connect/oauth2/authorize",map,String.class,HttpMethod.GET);
//        return rs;
    }

    //获取token的wx回调
    @GetMapping("getCodeBack")
    public void getCodeBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("进入回调");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String code = request.getParameter("code");//获取code
        logger.info("回掉获取CODE：{}",code);

//        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
//        params.add("accountId",accountID);
//        params.add("code",code);
//        String rs = HttpUtil.toReqPost(params,"http://wx.10086.cn/operation/api/out/getFansInfoByOauth2");

//        Map map = new HashMap();
//        map.put("accountId",accountID);
//        map.put("code",code);
//        String rs = HttpUtil.restTemplate("http://wx.10086.cn/operation/api/out/getFansInfoByOauth2",map,String.class,HttpMethod.GET);
        RestTemplate template = new RestTemplate();
        String url = getFansInfoByOauth2+"?accountId={accountId}&code={code}";

        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("accountId", accountID);
        uriVariables.put("code", code);
        String rs = template.getForObject(url, String.class, uriVariables);

        JSONObject jsonObject = JSONObject.parseObject(rs);
        logger.info("获取openId结果{}",jsonObject);
        StringBuffer backUrl = new StringBuffer(
                forendUrl+"#/?status="+URLEncoder.encode((String) jsonObject.get("status"), "UTF-8")+
                "&message="+URLEncoder.encode((String) jsonObject.get("message"), "UTF-8")+
                ""
        );
        if(jsonObject.get("openId")!=null){//正常返回大写openId
            backUrl.append("&openId="+URLEncoder.encode((String) jsonObject.get("openId"), "UTF-8"));
        }
        if(jsonObject.get("openid")!=null){//小写openid文档指明3001时不会返回openid 实际返回了 不过是小写
            backUrl.append("&openId="+URLEncoder.encode((String) jsonObject.get("openid"), "UTF-8"));
        }
        if(jsonObject.get("telNum")!=null){
            backUrl.append("&telNum="+URLEncoder.encode((String) jsonObject.get("telNum"), "UTF-8"));
        }
        if(jsonObject.get("provinceCode")!=null){
            backUrl.append("&provinceCode="+URLEncoder.encode((String) jsonObject.get("provinceCode"), "UTF-8"));
        }
        if(jsonObject.get("cityCode")!=null){
            backUrl.append("&cityCode="+URLEncoder.encode((String) jsonObject.get("cityCode"), "UTF-8"));
        }
        logger.info("回调前端：{}",backUrl.toString());
        response.sendRedirect(backUrl.toString());//登录状态发送
        //return rs;
    }

    //获取验证码
    @PostMapping("sendCode")
    public JSONObject sendCode(@RequestBody WxModel wxModel){
        logger.info("获取验证码，参数{}",wxModel);
        RestTemplate template = new RestTemplate();
        String url = sendCaptcha+"?openId={openId}&telNum={telNum}";
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("openId", wxModel.getOpenId());
        uriVariables.put("telNum", wxModel.getTelNum());
        String rs = template.getForObject(url, String.class, uriVariables);
        logger.info("获取验证码,结果：{}",rs);
        JSONObject jsonObject = JSONObject.parseObject(rs);
        return jsonObject;
    }

    //绑定用户手机号
    @PostMapping("loginBind")
    public JSONObject loginBind(@RequestBody WxModel wxModel){
        logger.info("绑定用户手机号,参数{}",wxModel);
        RestTemplate template = new RestTemplate();
        String url = telbindbycaptcha+"?openId={openId}&telNum={telNum}&captcha={captcha}";
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("openId", wxModel.getOpenId());
        uriVariables.put("telNum", wxModel.getTelNum());
        uriVariables.put("captcha", wxModel.getCaptcha());
        String rs = template.getForObject(url, String.class, uriVariables);
        logger.info("绑定用户手机号,结果：{}",rs);
        JSONObject jsonObject = JSONObject.parseObject(rs);
        return jsonObject;
    }


    //分享回调
    @GetMapping("fenxiang")
    public void fenxiang(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("进入分享");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String zuID = request.getParameter("zuID");//获取code
        logger.info("回掉获取zuID：{}",zuID);
        StringBuffer backUrl = new StringBuffer(
                forendUrl+"#/?zuID="+zuID+
                        ""
        );
        logger.info("回调前端：{}",backUrl.toString());
        response.sendRedirect(backUrl.toString());
    }


    //获取jsapi_ticket
    @GetMapping("getJSAPI")
    public JSONObject getJSAPI(){
        logger.info("进入获取JSAPI");
        Map map = new HashMap();
        map.put("accountId",accountID);
        map.put("url",forendUrl);
        String rs = HttpUtil.restTemplate(getJsSignature,map,String.class, HttpMethod.GET);
        JSONObject jsonObject = JSONObject.parseObject(rs);
        logger.info("获取结果：{}",jsonObject);
        return jsonObject;
    }
}
